﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WiseLinkWPF.Windows.Controls.GridView;
using CCF20Model;
using WiseLinkWPF.Windows.Controls;
using WiseLinkWPF.Windows.Data;
using System.Collections;
namespace CCF20
{
    /// <summary>
    /// Interaction logic for InStock.xaml
    /// </summary>
    public partial class InStock : UserControl
    {
        DeviceModel dm;
        CustomerModel cm;
        VehicleMaintenanceModel vrm;
        CCFZIC ccfZIC;
        private CollectionViewSource CustomerLookupView;
        
        public InStock()
        {
            
            InitializeComponent();

            ccfZIC = null;
            dm = new DeviceModel();
            cm = new CustomerModel();
            vrm = new VehicleMaintenanceModel();
            
            

        }
        private CCFZIC InitializeZIC()
        {
            if (ccfZIC == null)
            {
                ccfZIC = new CCFZIC();
            }
            return ccfZIC;
        }
        private void radGridView1_AddingNewDataItem(object sender, WiseLinkWPF.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
        {
            e.NewObject = new Device();
        }

        private void radGridView1_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
           if ((e.EditAction == GridViewEditAction.Commit) ||
               (e.EditOperationType == GridViewEditOperationType.Edit))
            {
               dm.Update();
               this.radGridView1.IsReadOnly = true;
               return;
            }
        }

        private void Instock_Add_Click(object sender, RoutedEventArgs e)
        {
            if (this.radGridView1.RowInEditMode != null)
            {
                this.radGridView1.RowInEditMode.CommitEdit();
            }
            string strAction = ((Button)sender).Content.ToString();
            string strUpdatedField = string.Empty;           
            string strUpdatedValue = string.Empty;
            Device selectedDevice = radGridView1.SelectedItem as Device;
            switch (strAction)
            {
                case "手动入库":
                    this.radGridView1.IsReadOnly = false;
                    this.radGridView1.BeginInsert();
                    this.radDataPager1.MoveToLastPage();
                    this.radGridView1.Items.MoveCurrentToLast();
                    return;
                case "售出":
                    SimpleCustomerInfo sci = (SimpleCustomerInfo)this.CustomerLookupComboBox.SelectedValue;
                    if (sci == null)
                    {
                        MessageBox.Show("请先选择客户", "CCF2.0", MessageBoxButton.OK);
                        return;
                    }

                    strUpdatedField = "Customer";
                    strUpdatedValue = sci.ID.ToString();
                    break;
                case "归库":

                    if ((selectedDevice != null) &&(selectedDevice.DeviceStatus != "售出"))
                    {
                        MessageBox.Show(string.Format("设备{0}还未售出不可以归库", selectedDevice.IDCSimNumber),
                                        "CCF2.0",
                                        MessageBoxButton.OK);
                        return;
                    }
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "库存";
                    break;
                
                case "发货入库":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "在途";
                    break;
                case "到货入库":
                    if ((selectedDevice != null) && (selectedDevice.DeviceStatus != "在途"))
                    {
                        MessageBox.Show(string.Format("设备{0}不处于在途状态,不可以到货入库", selectedDevice.IDCSimNumber),
                                        "CCF2.0",
                                        MessageBoxButton.OK);
                        return;
                    }
                    
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "库存";
                    break;
                case "到货索赔":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "索赔";
                    break;
                case "注册IDC":
                    strUpdatedField = "isRegistered";
                    break;
                case "特殊IDC":
                    strUpdatedField = "isSpecialIDC";
                    break;
                case "打印":
                    MyPrint myPrint = new MyPrint();
                    myPrint.MySource = this.radGridView1;
                    myPrint.PrintPreview();
                    myPrint.Show();
                    
                    return;
                case "列选项":
                    ChoseColumn myColumn = new ChoseColumn(null,this.radGridView1,"Device");
                    myColumn.ShowDialog();
                    return;
                    

            }
            UpdateDeviceStatus(strUpdatedField, strUpdatedValue);
        }

        private void UpdateDeviceStatus(string strUpdateField, string strUpdateValue)
        {
            if (strUpdateValue.Equals("在途"))
            {
                this.Dispatcher.BeginInvoke(new Action(() => 
                {
                    InitializeZIC().GetFHList(); 
                    this.radGridView1.ItemsSource = dm.GetDevice();
                }));
                return;
            }else if (this.radGridView1.SelectedItems.Count < 1)
            {
                MessageBox.Show("请先选中表格中的数据", "CCF2.0", MessageBoxButton.OK);
                return;
            }
            foreach (var item in this.radGridView1.SelectedItems)
            {
                var updatedItem = item as Device;
               
                if ((strUpdateField.Equals("isRegistered")
                    && (updatedItem.IsRegistered != null)
                    && ((bool)updatedItem.IsRegistered)))
                {
                    strUpdateField = "UnRegister";
                }

                if ((strUpdateField.Equals("isSpecialIDC") 
                    && (updatedItem.IsSpecialIDC != null)
                    && ((bool)updatedItem.IsSpecialIDC)))
                {
                    strUpdateField = "UnSpecialIDC";
                }
                switch (strUpdateField)
                {
                    case "Customer":
                        if (updatedItem.DeviceStatus=="售出")
                        {
                            MessageBox.Show(string.Format("设备已售出给客户:{0}，请先归库",updatedItem.Customer.Name), "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        else if (updatedItem.DeviceStatus != "库存")
                        {
                            MessageBox.Show(string.Format("设备还未入库，不可以销售"), "CCF2.0", MessageBoxButton.OK);
                            return;
                        }

                        try
                        {
                            CCF20Model.Customer customer = dm.GetCustomerByID(Convert.ToInt32(strUpdateValue));
                            updatedItem.Customer = customer;
                            updatedItem.Vehicle = customer.Vehicles.FirstOrDefault();
                            updatedItem.DeviceStatus = "售出";
                            updatedItem.SaleDate = DateTime.Now;
                            updatedItem.Sales = (string)Application.Current.Properties["CurrentUser"];

                            
                            
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            LoggerHelper.LogCCF20(ex.StackTrace);
                            return;
                        }
                        break;
                    case "DeviceStatus":
                        
                        if (strUpdateValue.Equals("库存"))
                        {
                            if ((updatedItem.IsRegistered!=null) &&(bool)updatedItem.IsRegistered)
                            {
                                MessageBox.Show("设备处于注册状态，不可以归库", "CCF2.0", MessageBoxButton.OK);
                                return;
                            }
                            updatedItem.DeviceStatus = strUpdateValue;
                            updatedItem.InStockDate = DateTime.Now;
                            updatedItem.Customer = null;
                            updatedItem.Vehicle = null;
                            // Also need to remove customer association in the Model
                            // remove the vehicle association
                            // Remove Maintenance association
                        }
                        break;
                    case "isRegistered":
                        if (!updatedItem.DeviceStatus.Equals("售出"))
                        {
                            MessageBox.Show("设备未售出，不可以注册", "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        //在注册时，我们自动加入更换机油的维护项目

                        MessageBoxResult confirm5101 = MessageBoxResult.No;
                        if (updatedItem.DeviceType.ToLower().Contains("tmt5101") ||
                            updatedItem.DeviceType.ToLower().Contains("tmt21"))
                        {
                            confirm5101 = MessageBox.Show(
                                                "请确认是否开通一键通导航服务",
                                                "CCF2.0",
                                                MessageBoxButton.YesNo);

                        }
                        if (InitializeZIC().DeviceRegister(updatedItem,
                                                  (confirm5101 == MessageBoxResult.Yes)?"1":"0"))
                        {
                            updatedItem.IsRegistered = true;
                            updatedItem.RegisterDate = DateTime.Now;
                            updatedItem.Vehicle.LastContactResult = "未联系";
                            vrm.AddDefaultMaintenanceToVehicle(updatedItem.Vehicle);
                            MessageBox.Show("注册成功");

                            if (InitializeZIC().UploadCustomerInfo(updatedItem))
                            {
                                MessageBox.Show("上传成功");
                            }
                        }
                        else
                        {
                            updatedItem.IsRegistered = false;
                        }
                        break;
                    case "UnRegister":

                            if ((updatedItem.IsSpecialIDC != null) &&(bool)updatedItem.IsSpecialIDC)
                            {
                                MessageBox.Show(
                                    string.Format("IDC{0} 是特殊IDC，请先取消特殊IDC注册", updatedItem.IDCSimNumber), "CCF2.0", MessageBoxButton.OK);
                                return;
                            }
                            MessageBoxResult confirmResult = MessageBox.Show(
                                string.Format("请确认取消注册选中的{0}个设备", radGridView1.SelectedItems.Count), "CCF2.0", MessageBoxButton.OKCancel);

                            if (confirmResult != MessageBoxResult.OK)
                            {
                                return;
                            }
                            if (InitializeZIC().DeviceUnRegister(updatedItem))
                            {
                                updatedItem.IsRegistered = false;
                                updatedItem.RegisterDate = null;
                                MessageBox.Show("取消注册成功");
                            }
                            
                        
                        break;
                    case "isSpecialIDC":

                        // Before you register a special IDC, you need to register first.
                        if ((updatedItem.IsRegistered == null)||!(bool)updatedItem.IsRegistered)
                        {
                            
                            MessageBox.Show(
                                string.Format("IDC{0} 还未注册", updatedItem.IDCSimNumber), "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        if (InitializeZIC().SpecialIDCRegister(updatedItem))
                        {
                            updatedItem.IsSpecialIDC = true;
                            MessageBox.Show("特殊IDC注册成功");
                        }
                        else
                        {
                            updatedItem.IsSpecialIDC = false;
                        }
                        break;
                    case "UnSpecialIDC":

                        if (InitializeZIC().SpecialIDCUnRegister(updatedItem))
                        {
                            updatedItem.IsSpecialIDC = false;
                            MessageBox.Show("取消特殊IDC注册成功");
                        }
                        break;
                }
                dm.Update();
                this.radGridView1.Items.Refresh();
            }
            
            
            
            //this.Dispatcher.BeginInvoke(new Action(() => this.radGridView1.Rebind()));
            
        }
        private void Instock_Delete_Click(object sender, RoutedEventArgs e)
        {
            int selectionCount = this.radGridView1.SelectedItems.Count;
            if (selectionCount == 0)
            {
                MessageBox.Show("请先选中表格中的数据", "CCF2.0", MessageBoxButton.OK);
                return;
            }
            foreach (var item in this.radGridView1.SelectedItems)
            {
                var removedItem = item as Device;
                if ((removedItem == null) || (removedItem.DeviceStatus == null))
                {
                    continue;
                }
                if (removedItem.DeviceStatus.Equals("售出"))
                {
                    MessageBox.Show("设备已售出，不可以删除", "CCF2.0", MessageBoxButton.OK);
                    return;
                }else if (removedItem.DeviceStatus.Equals("在途"))
                {
                    MessageBox.Show("设备在途，不可以删除", "CCF2.0", MessageBoxButton.OK);
                    return;
                }
            }
            MessageBoxResult confirmResult = MessageBox.Show(string.Format("请确认删除表格中的{0}条数据",selectionCount), "CCF2.0", MessageBoxButton.OKCancel);

            if (confirmResult != MessageBoxResult.OK)
            {
                return;
            }
            //QueryableCollectionView collectionView = (QueryableCollectionView)this.radGridView1.ItemsSource;
            //collectionView.Remove((Device)this.radGridView1.SelectedItem);
            
            ((IList)this.radGridView1.ItemsSource).Remove((Device)this.radGridView1.SelectedItem);
            this.Dispatcher.BeginInvoke(new Action(() => this.radGridView1.Rebind()));
            
        }

        private void radGridView1_SelectionChanged(object sender, WiseLinkWPF.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (e.AddedItems.FirstOrDefault() != null)
            {
                this.radGridView1.CurrentItem = e.AddedItems.First();
                ShowMaintenanceRecord();
              
            }
        }
        private void ShowMaintenanceRecord()
        {
            Device deviceData = this.radGridView1.CurrentItem as Device;
            if ((deviceData != null) && 
                (deviceData.DeviceStatus == "售出"))
            {
                //CurrentVehicleID = (int)deviceData.VehicleID;
                this.radMaintenanceRecord.CancelEdit();
                this.radMaintenanceRecord.ItemsSource = vrm.GetVehicleMaintenanceRecord(deviceData.Vehicle);
                GridViewComboBoxColumn maintenanceComboColumn = (GridViewComboBoxColumn)this.radMaintenanceRecord.Columns["MaintenanceType"];
                maintenanceComboColumn.ItemsSource = vrm.GetMaintenanceTypeByVehicle(deviceData.Vehicle);
                this.radMaintenanceRecord.ShowInsertRow = true;
            }
            else
            {
                this.radMaintenanceRecord.ItemsSource = null;
                this.radMaintenanceRecord.ShowInsertRow = false;
            }
            this.radMaintenanceRecord.Rebind();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            CustomerLookupView = (CollectionViewSource)this.FindResource("CustomerLookup");
            cm.GetSimpleCustomerInfo();
            CustomerLookupView.Source = cm.MySimpleCustomerInfo;
            this.radGridView1.ItemsSource = dm.GetDevice();
            
        }

        private void radMaintenanceRecord_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
            if (e.EditAction == GridViewEditAction.Commit)//|| e.EditOperationType == GridViewEditOperationType.Edit)
            {
                VehicleMaintenanceRecord vmr = (VehicleMaintenanceRecord)e.EditedItem;
                if (vmr == null || vmr.MaintenanceTypeID == null)
                {
                    e.Row.CancelEdit();
                    if (vmr != null)
                    {
                        ((IList)radMaintenanceRecord.ItemsSource).Remove(vmr);
                    }
                    return;
                }
                else
                {
                    vmr.Operator = (string)Application.Current.Properties["CurrentUser"];
                }
                
                vrm.Update();
                //if  (( vmr.ServiceMileage == null || vmr.ServiceMileage == 0 )

                //   &&( vmr.ServicePeriod == null || vmr.ServicePeriod == 0 ))
                //{
                //    MessageBox.Show("保养里程和保养周期不能全为空","CCF2.0", MessageBoxButton.OK);
                //}
                //else
                //{
                    
                //    vrm.Update();
                //}
            }

        }
        private void RadContextMenu_ItemClick(object sender, WiseLinkWPF.Windows.RadRoutedEventArgs e)
        {
            RadContextMenu menu = (RadContextMenu)sender;
            RadMenuItem clickedItem = e.OriginalSource as RadMenuItem;
            GridViewRow row = menu.GetClickedElement<GridViewRow>();

            //radMaintenanceRecord.SelectedItem = row;
            if (clickedItem != null && row != null)
            {
                string header = Convert.ToString(clickedItem.Header);

                if (header == "删除")
                {

                    ((IList)this.radMaintenanceRecord.ItemsSource).Remove(row.Item);
                    vrm.Update();

                }
            }
        }
        private void ApplyServiceDateMileage_Click(object sender, RoutedEventArgs e)
        {
            int? Mileage = Convert.ToInt32(this.LastServiceMileage.Value);
            DateTime? ServiceDate = this.LastServiceDate.SelectedDate;

            if ((Mileage == null) || (ServiceDate == null))
            {
                MessageBox.Show("最新服务里程和最新服务时间不可为空", "CCF 2.0", MessageBoxButton.OK);
                return;
            }

            
            foreach (var r in radMaintenanceRecord.Items)
            {
                VehicleMaintenanceRecord mtd = r as VehicleMaintenanceRecord;
                if (mtd != null)
                {
                    mtd.LastServiceDate = ServiceDate;
                    mtd.LastServiceMileage = Mileage;
                }
            }
            vrm.Update();
            

        }

        private void radGridView1_CellValidating(object sender, GridViewCellValidatingEventArgs e)
        {
            // if there is no change of the value, no need to validate.
            if (e.NewValue == e.OldValue) return;
            GridViewCell cell = e.Cell;
            string validationText = string.Empty;

            switch (cell.Column.UniqueName)
            {
                case "IDC号":
                    
                    if (dm.IsDuplicateDevice((e.NewValue as string), "IDCSimNum"))
                    {
                        validationText="重复的设备SIM卡号";
                    }
                    break;
                case "产品序列号":
                    
                    if (dm.IsDuplicateDevice((e.NewValue as string), "DeviceKey"))
                    {
                        validationText="重复的设备序列号";
                    }
                    break;
                case "MaintenanceType":
                    
                    GridViewRow row = (GridViewRow)e.Cell.ParentRow;
                    int mtTypeId;
                    MaintenanceType mt;
                    if (Int32.TryParse(e.NewValue.ToString(),out mtTypeId))
                    {
                        Device deviceData = this.radGridView1.CurrentItem as Device;
                        if (mtTypeId == 0)
                        {
                            validationText = "保养项目不可为空";
                        }
                        else
                        {
                            mt = vrm.GetMaintenanceType(mtTypeId);

                            if (!vrm.IsDuplicate(deviceData.VehicleID, mtTypeId, mt.Priority ?? 1))
                            {
                                ((VehicleMaintenanceRecord)row.DataContext).ServiceMileage = mt.ServiceMileage;
                                ((VehicleMaintenanceRecord)row.DataContext).ServicePeriod = mt.ServicePeriod;
                                ((VehicleMaintenanceRecord)row.DataContext).LastServiceDate = deviceData.Vehicle.LastServcieDate;
                                ((VehicleMaintenanceRecord)row.DataContext).LastServiceMileage = deviceData.Vehicle.LastServiceMileage;
                                ((VehicleMaintenanceRecord)row.DataContext).Priority = mt.Priority;
                                ((VehicleMaintenanceRecord)row.DataContext).AnchiID = mt.AnchiID;
                                vrm.Update();
                            }
                            else
                            {
                                validationText = "重复的保养项目";
                            }
                        }
                    }
                    else
                    {
                        validationText = "无法找到正确的保养项目";
                    }
                    
                    break;
                default:
                    break;
            }
            if (!string.IsNullOrEmpty(validationText))
            {
                ToolTipService.SetToolTip(cell, validationText);
                e.IsValid = false;
                e.ErrorMessage = validationText;

            }

        }

        private List<Device> PagedData()
        {
            List<Device> printData = this.radDataPager1.Source.OfType<Device>().ToList();
            return printData;
        }
        private void radMaintenanceRecord_BeginningEdit(object sender, GridViewBeginningEditRoutedEventArgs e)
        {
            
            if (this.radMaintenanceRecord.Items.Count > 0)
            {
                e.Row.IsSelected = true;
                this.radMaintenanceRecord.SelectedItem = this.radMaintenanceRecord.Items[0];
            }
        }

        private void radMaintenanceRecord_CellValidated(object sender, GridViewCellValidatedEventArgs e)
        {
            if (e.ValidationResult.ErrorMessage != null)
            {
                this.radMaintenanceRecord.CancelEdit();
            } 
 
        }

    }
}
